package monster.com.cvh.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import butterknife.BindView;
import monster.com.cvh.R;
import monster.com.cvh.bean.ResultBean;
import monster.com.cvh.bean.ResumeSmallBean;
import monster.com.cvh.bean.ResumeTemplateBean;
import monster.com.cvh.database.GreenDAOManager;
import monster.com.cvh.database.ResumeInfoBean;
import monster.com.cvh.event.RefreshResumePreviewEvent;
import monster.com.cvh.event.VisitorRefreshEvent;
import monster.com.cvh.fragment.base.PermissionFragment;
import monster.com.cvh.gen.ResumeInfoBeanDao;
import monster.com.cvh.listener.ItemClickListener;
import monster.com.cvh.util.DensityUtils;
import monster.com.cvh.util.KeyboardUtils;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.view.ResumePopupWindow;
import okhttp3.Call;
import okhttp3.Response;


/**
 * @author: 13580
 * @data: 2018/4/10
 * @function:简历模板预览Fragment
 */
public class UserResumeFragment extends PermissionFragment implements ItemClickListener, Observer {
    private static final String TAG = "UserResumeFragment";
    @BindView(R.id.webview_fragment_user_resume)
    WebView mWebView;
    @BindView(R.id.srl_fragment_user_resume_wrapper)
    SmartRefreshLayout mWrapper;
    private ResumePopupWindow mPopupWindow;
    private int mResumeId = 1;
    private String mCurrentUrl;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RefreshResumePreviewEvent.getInstance().addObserver(this);
        VisitorRefreshEvent.getInstance().addObserver(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefreshResumePreviewEvent.getInstance().deleteObserver(this);
        VisitorRefreshEvent.getInstance().deleteObserver(this);
        OkGo.getInstance().cancelTag(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_user_resume;
    }

    @Override
    protected void initData() {
        if (mPopupWindow == null) {
            mPopupWindow = new ResumePopupWindow(getActivity().getApplicationContext(), this);
        }
    }

    @Override
    protected void initEvent() {
        final ResumeInfoBeanDao dao = GreenDAOManager.getInstance().getmDaoSession().getResumeInfoBeanDao();
        List<ResumeInfoBean> list = dao.queryBuilder().list();
        if (list != null && list.size() > 0) {
            mResumeId = list.get(list.size() - 1).getResumeId();
        }
        initWebView();
        mWrapper.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshWebView();
                mWrapper.finishRefresh();
            }
        });
    }

    private void initWebView() {
        final WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setSupportZoom(true);
        webSettings.setLoadWithOverviewMode(true);
        //自定义错误页面
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //6.0以下执行
                Log.i(TAG, "onReceivedError: ------->errorCode" + errorCode + ":" + description);
                //网络未连接
                if (view != null) {
                    view.loadUrl("about:blank");
                }
            }

            //处理网页加载失败时
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                //6.0以上执行
                Log.i(TAG, "onReceivedError: ");
                if (view != null) {
                    view.loadUrl("about:blank");
                }
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }
        });


        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;
        if (mDensity >= 240) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == 160) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if (mDensity == 120) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        } else {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        }
        mWebView.setOnTouchListener(new View.OnTouchListener() {
            float startX = 0;
            float starty = 0;
            float endX = 0;
            float endY = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_DOWN) {
                    KeyboardUtils.hideSoftInput((Activity) mContext);
                    startX = motionEvent.getX();
                    starty = motionEvent.getY();
                }

                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
                    endX = motionEvent.getX();
                    endY = motionEvent.getY();
                    float x = Math.abs(endX - startX);
                    float y = Math.abs(endY - starty);
                    int scaledDoubleTapSlop = DensityUtils.dp2px(getContext(), 1.5f);
                    if (x < scaledDoubleTapSlop || y < scaledDoubleTapSlop) {
                        setDialog();
                        return true;
                    }

                }
                return false;
            }
        });
        String token = SPUtils.getString(getContext(), MyConstant.TOKEN, "");
        if (token.isEmpty()) {
            mCurrentUrl = MyConstant.RESUME_TEMPLATES_URL + mResumeId;
        } else {
            mCurrentUrl = MyConstant.RESUME_TEMPLATES_URL + mResumeId + "?token=" + token;
        }
        if (mWebView != null && !mCurrentUrl.equals("")) {
            mWebView.loadUrl(mCurrentUrl);
        }
    }

    @Override
    public void loadBigImage(final String url) {
        Log.e(TAG, "网址: " + url);
        mCurrentUrl = url;
        if (!mCurrentUrl.equals("") && mWebView != null) {
            mWebView.loadUrl(mCurrentUrl);
        }
    }

    /**
     * 显示窗口
     */
    public void setDialog() {
        if (mPopupWindow != null) {
            if (mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            } else {
                //设置layout在PopupWindow中显示的位置
                mPopupWindow.showAtLocation(mWrapper, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        }
    }

    public void refreshWebView() {
        String token = SPUtils.getString(getContext(), MyConstant.TOKEN, "");
        if (token.isEmpty()) {
            mCurrentUrl = MyConstant.RESUME_TEMPLATES_URL + mResumeId;
        } else {
            mCurrentUrl = MyConstant.RESUME_TEMPLATES_URL + mResumeId + "?token=" + token;
        }
        if (mPopupWindow!=null){
            mPopupWindow.refreshData();
        }
        if (mCurrentUrl != null) {
            loadBigImage(mCurrentUrl);
        }
    }

    public void setResumeId(int resumeId) {
        this.mResumeId = resumeId;
    }

    @Override
    public void update(Observable observable, Object o) {
        if (observable instanceof RefreshResumePreviewEvent && mPopupWindow != null) {
            final List<ResumeTemplateBean> mData = new ArrayList<>();
            OkGo.<String>get(MyConstant.GET_DEFAULT_TEMPLATES)
                    .tag(this)
                    .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            try {
                                ResumeSmallBean bean = new Gson().fromJson(s, ResumeSmallBean.class);
                                if (bean != null && bean.getCode() == 1) {
                                    List<ResumeSmallBean.DataBean> data = bean.getData();
                                    for (ResumeSmallBean.DataBean dataBean : data) {
                                        mData.add(new ResumeTemplateBean(dataBean.getId(), dataBean.isIs_lock(), dataBean.getCover_image_url()));
                                    }
                                    final ResumeInfoBeanDao dao = GreenDAOManager.getInstance().getmDaoSession().getResumeInfoBeanDao();
                                    List<ResumeInfoBean> list = dao.queryBuilder().list();
                                    for (ResumeInfoBean resumeInfoBean : list) {
                                        mData.add(0, new ResumeTemplateBean(resumeInfoBean.getResumeId(), resumeInfoBean.getIsLock(), resumeInfoBean.getFilePath()));
                                    }
                                    mPopupWindow.setNewDate(mData);
                                }
                            } catch (JsonSyntaxException e) {
                                ResultBean bean = new Gson().fromJson(s, ResultBean.class);
                                if (bean.getCode() == -1003) {
                                    goToLogin();
                                } else {
                                    showToastShort(R.string.net_load_failed);
                                }
                                e.printStackTrace();
                            }
                        }
                    });
        }

        if (observable instanceof VisitorRefreshEvent) {
            refreshWebView();
        }
    }
}
